import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { User, LoginRequest, RegisterRequest, LoginResponse } from '@/types'
import { login as loginApi, register as registerApi } from '@/api'
import { setToken, getToken, setUserInfo, getUserInfo, clearStorage } from '@/utils/storage'

// 认证状态管理
export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(getUserInfo())
  const token = ref<string | null>(getToken())
  const isLoading = ref<boolean>(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)

  // 操作

  /**
   * 用户登录
   * @param data 登录请求数据
   */
  const login = async (data: LoginRequest) => {
    isLoading.value = true
    try {
      const response = await loginApi(data)
      // 保存token和用户信息
      token.value = response.token
      setToken(response.token)
      // 构建用户信息
      user.value = {
        user_id: response.user_id,
        username: response.username,
        email: '', // 登录接口返回的用户信息中没有email，需要后续获取
        created_at: ''
      }
      setUserInfo(user.value)
      return response
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 用户注册
   * @param data 注册请求数据
   */
  const register = async (data: RegisterRequest) => {
    isLoading.value = true
    try {
      const response = await registerApi(data)
      return response
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 用户登出
   */
  const logout = () => {
    // 清除状态
    user.value = null
    token.value = null
    // 清除本地存储
    clearStorage()
  }

  /**
   * 更新用户信息
   * @param newUserInfo 新的用户信息
   */
  const updateUserInfo = (newUserInfo: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...newUserInfo }
      setUserInfo(user.value)
    }
  }

  return {
    user,
    token,
    isLoading,
    isAuthenticated,
    login,
    register,
    logout,
    updateUserInfo
  }
})
